#pragma once
#include <iostream>
#include <vector>
#include <cassert>

namespace wxd
{
    template <class T>
    class Less
    {
    public:
        bool operator()(const T &x, const T &y)
        {
            return x < y;
        }
    };

    template<class T>
    class Greater
    {
    public:
        bool operator()(const T &x, const T &y)
        {
            return x > y;
        }
    };

    template <class T, class Container = std::vector<T>,class Compare = Less<T>>
    class priority_queue
    {
    private:
        // 向上调整
        void AdjustUp()
        {
            int child = _con.size() - 1;
            int parent = (child - 1) / 2;
            while (child != 0)
            {
                
                if ( _cmp(_con[parent],_con[child]))
                {
                    std::swap(_con[child], _con[parent]);
                }
                else
                {
                    break;
                }
                child = parent;
                parent = (child - 1) / 2;
            }
        }
        // 向下调整建堆
        void AdjustDown()
        {
            int range = _con.size() - 1;
            int parent = 0;
            int child = parent * 2 + 1;
            while (child <= range)
            {
                // 调整child
                if (child + 1 <= _con.size() - 1 && _cmp(_con[child],_con[child + 1]))
                {
                    child += 1;
                }

                if (_cmp(_con[parent],_con[child]))
                {
                    std::swap(_con[parent], _con[child]);
                }
                else
                {
                    break;
                }

                parent = child;
                child = parent * 2 + 1;
            }
        }

    public:
        // 构造函数
        priority_queue() {}
        // 拷贝构造
        priority_queue(const priority_queue &p)
        {
            _con = p._con;
        }
        // push
        void push(const T &val);
        void pop();
        const T &top() const
        {
            return _con.front();
        }
        size_t size() const
        {
            return _con.size();
        }
        bool empty() const
        {
            return _con.empty();
        }

        // private:
        Container _con;
        Compare _cmp;
    };

    template <class T, class Container,class Compare>
    void priority_queue<T, Container,Compare>::push(const T &val)
    {
        // 先插入
        _con.push_back(val);
        // 向上调整
        AdjustUp();
    }

    template <class T, class Container,class Compare>
    void priority_queue<T, Container,Compare>::pop()
    {
        assert(!_con.empty());
        // 交换
        std::swap(_con[0], _con[_con.size() - 1]);
        // 删除
        _con.pop_back();
        // 向下调整建堆
        AdjustDown();
    }
};